package com.mzhmxh.control;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mzhmxh.pojo.SmbmsUser;
import com.mzhmxh.pojo.UserPhoto;
import com.mzhmxh.service.UserPhotoService;
import com.mzhmxh.service.UserService;
import com.mzhmxh.util.CodeUtil;
import com.mzhmxh.util.DateUtil;
import com.mzhmxh.util.FileUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author LiJinCheng
 * @Date 2020/7/10 7:57 下午
 * @Version 1.0
 * @package com.cheng.control
 **/
@Controller
@RequestMapping("/user")
public class UserControl {

    @Autowired
    private UserService userService;
    @Autowired
    private UserPhotoService photoService;

    @RequestMapping("/")
    public String login() {
        return "index";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public String doLogin(SmbmsUser user, String name, String pass, String code, JsonMapper mapper, HttpSession session) {
        System.out.println(name);
        try {
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random.equals(code)) {
                user.setUsercode(name);
                user.setUserpassword(pass);
                SmbmsUser smbmsUser = userService.selectByPrimaryKey(user);
                if (smbmsUser != null) {
                    session.setAttribute("user", smbmsUser);
                    return mapper.writeValueAsString("success");
                } else {
                    return "error";
                }
            } else {
                return "code";
            }
        } catch (Exception e) {
            return "fail";
        }
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        try {
            CodeUtil.getRandCode(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/list")
    public String list() {
        return "user/list";
    }

    @RequestMapping("/getList")
    @ResponseBody
    public String getList(JsonMapper mapper, SmbmsUser user, Integer curr, String username, Integer userrole) {
        try {
            if (null == curr) {
                curr = 1;
            }
            if (username.trim() != null) {
                user.setUsername(username);
            }
            if (userrole != null) {
                user.setUserrole(Long.valueOf(userrole));
            }
            System.out.println(user);
            PageHelper.startPage(curr, 5);
            List<Map<String, Object>> list = userService.getList(user);
            return mapper.writeValueAsString(list);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/getPage")
    @ResponseBody
    public String getPage(JsonMapper mapper, SmbmsUser user, Integer curr, String username, Integer userrole) {
        try {
            if (null == curr) {
                curr = 1;
            }
            if (username != null) {
                user.setUsername(username);
            }
            if (userrole != null) {
                user.setUserrole(Long.valueOf(userrole));
            }
            PageHelper.startPage(curr, 5);
            List<Map<String, Object>> list = userService.getList(user);
            PageInfo pageInfo = new PageInfo(list);
            Map<String, Object> map = new HashMap<>();
            map.put("pagess", pageInfo.getPages());
            map.put("pageNum", pageInfo.getPageNum());
            map.put("totals", pageInfo.getTotal());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/view")
    public String view(Model model, Integer userid) {
        Map<String, Object> userOne = userService.getUserOne(Long.valueOf(userid));
        model.addAttribute("user_view", userOne);
        UserPhoto id1 = photoService.selectByPrimaryKey(Integer.valueOf(userOne.get("id").toString()));
        model.addAttribute("p", id1);
        return "user/view";
    }

    @RequestMapping("/getByCode")
    @ResponseBody
    public String getByCode(JsonMapper mapper, String code) {
        try {
            SmbmsUser user = userService.selectByCOde(code);
            if (user != null) {
                return mapper.writeValueAsString("exist");
            } else {
                return mapper.writeValueAsString("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/doAdd")
    public String doAdd(SmbmsUser user, String birthdays, HttpServletRequest request, UserPhoto photo) {
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthdays));
            /*SmbmsUser u = (SmbmsUser)request.getSession().getAttribute("user");
            user.setCreatedby(u.getId());
            */
            user.setCreationdate(new SimpleDateFormat(DateUtil.FORMAT).parse(DateUtil.getDateTime()));
            userService.insertSelective(user);
            SmbmsUser user1 = userService.selectByCOde(user.getUsercode());
            String path = "/Users/lijincheng/IdeaProjects/1000phone/src/main/web/upload/";
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            int i = 0;
            String[] s = new String[2];
            for (MultipartFile file : files) {
                try {
                    s[i] = FileUtil.uploadFile(file, path, user.getUsercode() + "_" + i);
                    i++;
                } catch (Exception e) {

                    return "userError";
                }
            }
            photo.setId(0);
            photo.setUserId(Math.toIntExact(user1.getId()));
            photo.setPhontoName1(s[0]);
            photo.setPhontoName2(s[1]);
            photoService.insertSelective(photo);
            return "user/list";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/modify")
    public String modify(Model model, Integer userid) {
        model.addAttribute("userInfo", userService.getUserOne(Long.valueOf(userid)));
        return "user/modify";
    }

    @RequestMapping("/doModify")
    public String doModify(SmbmsUser user, String birthdays, HttpServletRequest request, UserPhoto photo) {
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthdays));
            SmbmsUser u = (SmbmsUser) request.getSession().getAttribute("user");
            user.setModifyby(u.getId());
            user.setModifydate(new SimpleDateFormat(DateUtil.FORMAT).parse(DateUtil.getDateTime()));
            userService.updateByPrimaryKeySelective(user);
            SmbmsUser user1 = userService.selectByCOde(user.getUsercode());
            String path = "/Users/lijincheng/IdeaProjects/1000phone/src/main/web/upload/";
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            int i = 0;
            String[] s = new String[2];
            for (MultipartFile file : files) {
                try {
                    s[i] = FileUtil.uploadFile(file, path, user.getUsercode() + "_" + i);
                    i++;
                } catch (Exception e) {

                    return "userError";
                }
            }
            if (s[0] != null) {
                photo.setPhontoName1(s[0]);
            }
            if (s[1] != null) {
                photo.setPhontoName2(s[1]);
            } else {
                photo.setPhontoName1(null);
                photo.setPhontoName2(null);
            }
            photo.setId(0);
            photo.setUserId(Math.toIntExact(user1.getId()));
            photoService.updateByPrimaryKeySelective(photo);
            return "user/list";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/pwdModify")
    public String pwdModify() {
        return "user/passmodify";
    }

    @RequestMapping("/getOldPwd")
    @ResponseBody
    public Object getPwdByUserId(JsonMapper mapper,String oldpassword, HttpSession session) {
        try {

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (null == session.getAttribute("user")) {//session过期
            resultMap.put("result", "sessionerror");
        } else if (oldpassword.isEmpty() || oldpassword == null) {//旧密码输入为空
            resultMap.put("result", "error");
        } else {
            String sessionPwd = ((SmbmsUser) session.getAttribute("user")).getUserpassword();
            if (oldpassword.equals(sessionPwd)) {
                resultMap.put("result", "true");
            } else {//旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        return mapper.writeValueAsString(resultMap);

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/pwdSave")
    @ResponseBody
    public String pwdSave(JsonMapper mapper,String newpassword,HttpSession session){
        try {
            SmbmsUser user = (SmbmsUser) session.getAttribute("user");
            if (user!=null && newpassword!=null){
                user.setUserpassword(newpassword);
                int i = userService.updateByPrimaryKeySelective(user);
                if (i==1){
                    session.removeAttribute("user");
                    return mapper.writeValueAsString("success");
                }else {
                    return mapper.writeValueAsString("fail");
                }
            }
            return mapper.writeValueAsString("fail");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        session.removeAttribute("user");
        return "index";
    }

}
